package com.tripcube.ai.service.impl;

import com.tripcube.ai.model.dto.BaseChatDTO;
import com.tripcube.ai.model.vo.BaseChatVO;
import com.tripcube.ai.service.BaseChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

/**
 * 基础聊天服务实现类
 * 实现AI聊天相关的基础功能，包括简单聊天、流式聊天和记忆聊天
 * 
 * @author alander
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class BaseChatServiceImpl implements BaseChatService {

    /**
     * DashScope聊天客户端
     */
    private final ChatClient dashScopeChatClient;

    /**
     * 简单聊天实现
     * DashScope API进行基础的AI对话
     * 
     * @param request 聊天请求参数
     * @return 聊天响应结果
     */
    @Override
    public BaseChatVO simpleChat(BaseChatDTO request) {
        log.info("开始简单聊天，查询内容: {}", request.getQuery());
        
        String content = dashScopeChatClient
                .prompt(request.getQuery())
                .call()
                .content();

        BaseChatVO response = new BaseChatVO();
        response.setContent(content);
        response.setConversationId(request.getConversationId());

        log.info("简单聊天完成，响应长度: {} 字符", content.length());

        return response;
    }

    /**
     * 流式聊天实现
     * 调用DashScope API进行流式AI对话，实时返回响应内容
     * 
     * @param request 聊天请求参数
     * @return 流式聊天响应
     */
    @Override
    public Flux<String> streamChat(BaseChatDTO request) {
        log.info("开始流式聊天，查询内容: {}", request.getQuery());
        
        Flux<String> content = dashScopeChatClient
                .prompt(request.getQuery())
                .stream()
                .content();

        return content.doOnComplete(() -> log.info("流式聊天完成"))
                     .doOnError(error -> log.error("流式聊天出错: {}", error.getMessage()));
    }

    /**
     * 带对话记忆的聊天实现
     * 基于会话ID进行具有上下文记忆功能的AI对话
     * 
     * @param request 聊天请求参数，需包含会话ID
     * @return 流式聊天响应
     */
    @Override
    public Flux<String> advisorChat(BaseChatDTO request) {
        log.info("开始记忆聊天，会话ID: {}, 查询内容: {}", 
                request.getConversationId(), request.getQuery());
        
        return dashScopeChatClient
                .prompt(request.getQuery())
                .advisors(a -> a.param("CHAT_MEMORY_CONVERSATION_ID_KEY", request.getConversationId()))
                .stream()
                .content()
                .doOnComplete(() -> log.info("记忆聊天完成，会话ID: {}", request.getConversationId()))
                .doOnError(error -> log.error("记忆聊天出错，会话ID: {}, 错误: {}", 
                        request.getConversationId(), error.getMessage()));
    }
}
